// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	SmartLib
//  File name:	LockerByKey.cs
//  Developer:	Igor Solomatov
//  Created:	15.03.2013
// 
// -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Threading;

namespace Smart
{
	/// <summary>
	/// Key locker
	/// </summary>
	public class LockerByKey
	{
		protected ReaderWriterLockSlim SyncObj;
		protected Dictionary<string, object> KeyLocks;

		public LockerByKey()
		{
			SyncObj = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
			KeyLocks = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
		}

		public ObjectLocker By(string key)
		{
			return new ObjectLocker(KeyLocks.SafeGetLoad(key, SyncObj, newKey => new object()));
		}
	}
}